package logic

import (
	"context"
	"fmt"
	"strconv"
	"time"
	"xialou_platform/app/errorx"
	"xialou_platform/services/agent/model"

	"xialou_platform/services/agent/rpc/agentClient"
	"xialou_platform/services/agent/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AgentAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAgentAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AgentAddLogic {
	return &AgentAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 新增代理商
func (l *AgentAddLogic) AgentAdd(in *agentClient.AgentParam) (*agentClient.IdBody, error) {

	var parentUid int64
	var topUid int64
	if in.ParentUid > 0 {
		parentAgent, err := l.svcCtx.AgentModel.FindOne(l.ctx, in.ParentUid)
		if err != nil {
			return nil, err
		}
		// 认证成功的才可以绑定
		if parentAgent.Status == 2 {
			switch parentAgent.Type {
			case 1:
				parentUid = parentAgent.ParentUid
				topUid = parentAgent.TopUid
			case 2:
				parentUid = parentAgent.Id
				topUid = parentAgent.TopUid
			case 3:
				parentUid = parentAgent.Id
				topUid = parentAgent.Id
			}
		}
	}

	id := l.svcCtx.Flake.Generate().Int64()
	nowTime := time.Now()
	newIdStr := strconv.FormatInt(id, 10)
	nickName := fmt.Sprintf("%s%s", "SK", newIdStr[len(newIdStr)-6:])
	_, err := l.svcCtx.AgentModel.Insert(l.ctx, &model.Agent{
		Id:                      id,
		Avatar:                  "https://imgs.ynz666.com/xiuxian/avatar.png",
		Name:                    nickName,
		Gender:                  in.Gender,
		Phone:                   in.Phone,
		Status:                  in.Status,
		Type:                    in.Type,
		IdCard:                  in.IdCard,
		RealName:                nickName,
		Company:                 in.Company,
		BusinessLicense:         in.BusinessLicense,
		UnifiedSocialCreditCode: in.UnifiedSocialCreditCode,
		CreateTime:              nowTime,
		CreateBy:                id,
		UpdateTime:              nowTime,
		UpdateBy:                id,
		DelFlag:                 false,
		OpenId:                  in.OpenId,
		UnionId:                 in.UnionId,
		StoreNum:                20, // 默认20个商家
		ParentUid:               parentUid,
		TopUid:                  topUid,
		ProfitRate:              30,
		CardRate:                50,
		InviteUid:               in.ParentUid,
	})
	if err != nil {
		return nil, errorx.NewReasonError("网络出小差了，请重试刷新再试。", err.Error())
	}

	return &agentClient.IdBody{
		Id: id,
	}, nil
}
